<template>
    <div>
        <!-- 添加按钮 -->
        <el-button type="primary" @click="openDialog()">添加轮播图</el-button>

        <el-table class="custom-table" :data="carouselList" style="width: 65%;margin-left: 10%;" stripe border>
            <!-- 序号 -->
            <el-table-column type="index" label="序号" width="50" />

            <!-- 轮播图ID -->
            <el-table-column prop="carouselId" label="ID" width="80" />

            <!-- 轮播图名字 -->
            <el-table-column prop="carouselName" label="轮播图名字" width="120" />

            <!-- 轮播图图片 -->
            <el-table-column prop="url" label="轮播图图片" width="220">
                <template #default="{ row }">
                    <el-image style="width: 100px; height: 60px" :src="row.url" fit="cover"
                        :preview-src-list="[row.url]" />
                </template>
            </el-table-column>

            <!-- 创建时间 -->
            <el-table-column prop="created_at" label="创建时间" width="180">
                <template #default="{ row }">
                    <span>{{ row.createdAt }}</span>
                </template>
            </el-table-column>

            <!-- 更新时间 -->
            <el-table-column prop="updated_at" label="更新时间" width="180">
                <template #default="{ row }">
                    <span>{{ row.updatedAt }}</span>
                </template>
            </el-table-column>

            <!-- 状态列 -->
            <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                        {{ row.status === 1 ? '展示' : '不展示' }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="180">
                <template #default="{ row }">
                    <el-button type="text" size="small" @click="editCarousel(row)">编辑</el-button>
                    <el-button type="text" size="small" @click="deleteCarousel(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑弹窗 -->
        <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
            @on-close="onClose" @on-confirm="commit">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="图片名字" prop="carouselName">
                    <el-input v-model="form.carouselName" placeholder="请输入图片名字"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择状态">
                        <el-option label="展示" :value="1" />
                        <el-option label="不展示" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片预览">
                    <!-- 当有图片URL时显示图片；否则显示“暂无图片”提示 -->
                    <el-image v-if="form.url" style="width: 200px; height: 120px" :src="form.url" fit="cover"
                        :preview-src-list="[form.url]">
                    </el-image>
                    <div v-else
                        style="width: 200px; height: 120px; background: #f5f5f5; display: flex; align-items: center; justify-content: center; color: #999;">
                        暂无图片
                    </div>
                </el-form-item>

            </el-form>
            <UploadImg></UploadImg>
        </Dialog>

    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import type { Carousel } from '@/api/carousel/carouselTable';
import { addCarouselApi, deleteCarouseApi, editCarouselApi, getCarouselApi } from '@/api/carousel';
import useDialog from '@/hooks/usedialog';
import Dialog from '@/components/dialog/Dialog.vue';
import UploadImg from '@/components/upload/UploadImg.vue';
import { useImageUrlStore } from '@/store/imgUrl';
//弹窗数据
//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog();
//获取图片数据
const useImage = useImageUrlStore()


// 表格数据
const carouselList = ref<Carousel[]>([]);

const dialogVisible = ref(false);
const dialogTitle = ref('');

// 表单引用和数据对象
const formRef = ref<FormInstance>();
const form = reactive<Carousel>({
    carouselId: '',
    carouselName: '',
    url: '',
    status: '',
    createdAt: '',
    updatedAt: ''
});
const initialForm = reactive<Carousel>({
    carouselId: '',
    carouselName: '',
    url: '',
    status: '',
    createdAt: '',
    updatedAt: ''
});

// 表单验证规则
const rules = reactive({
    carouselName: [
        { required: true, message: '请输入图片名字', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
});

//获取轮播图数据
const fetchCarousels = async () => {
    const res = await getCarouselApi()
    if (res.code == 200) {
        carouselList.value = res.data
        ElMessage.success(res.msg)
    }
};

// 打开新增弹窗
const openDialog = () => {
    dialog.visible = true
    dialog.title = "新增轮播图"
};

// 打开编辑弹窗
const editCarousel = (row: Carousel) => {
    dialog.visible = true
    dialog.title = "编辑轮播图"
    Object.assign(form, row);
    dialogVisible.value = true;
};

// 删除轮播图
const deleteCarousel = async (row: Carousel) => {
    // 可加入删除确认
    const res = await deleteCarouseApi(row.carouselId)
    if(res.code==200){
        ElMessage.success(res.msg)
        fetchCarousels()
    }
};

// 提交表单（新增或编辑）
const commit = () => {
    formRef.value?.validate(async (valid) => {
        if (valid) {
            if (dialog.title == "新增轮播图") {
                if (useImage.getImageUrl) {
                    form.url = useImage.getImageUrl
                    const res = await addCarouselApi(form)
                    if (res.code == 200) {
                        ElMessage.success(res.msg)
                        onClose()
                        fetchCarousels()
                        useImage.deleteImageUrl()
                        Object.assign(form, initialForm)
                    }
                }
            }
            if (dialog.title == "编辑轮播图") {
                if (useImage.getImageUrl) {
                    form.url = useImage.getImageUrl
                }
                const res = await editCarouselApi(form)
                if (res.code) {
                    ElMessage.success(res.msg)
                    onClose()
                    fetchCarousels()
                    useImage.deleteImageUrl()
                    Object.assign(form, initialForm)
                }


            }


        }

    })

};

onMounted(() => {
    fetchCarousels();
});
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style>